//
//  YzPickerView.m
//  自定义选择器
//
//  Created by hjg on 2016/10/27.
//  Copyright © 2016年 hjg. All rights reserved.
//

#import "YzPickerView.h"
#import "Masonry.h"

//16进制颜色转换
#define kColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
//设置字体
#define FONT(size) [UIFont systemFontOfSize:size]
//设置颜色
#define COLOR(r,g,b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]
#define SAME_COLOR(value) COLOR(value,value,value)
//屏幕宽度和高度
#define screenW [UIScreen mainScreen].bounds.size.width
#define screenH [UIScreen mainScreen].bounds.size.height
//固定浅蓝色
#define globalColor [UIColor colorWithRed:93/255.0 green:198/255.0 blue:197/255.0 alpha:1]
//是否是3.5英寸
#define is3inch ([UIScreen mainScreen].bounds.size.height == 480)
//是否4英寸
#define is4inch ([UIScreen mainScreen].bounds.size.height == 568)
//是否4.7英寸
#define is47inch ([UIScreen mainScreen].bounds.size.height == 667)
//是否5.5英寸
#define is55inch ([UIScreen mainScreen].bounds.size.height == 736)

@interface YzPickerView () <UIPickerViewDataSource,UIPickerViewDelegate>
{
    NSArray *_AllARY;          //取出所有数据(json类型，在pilst里面)
    NSMutableArray *_ProvinceAry;          //只装省份的数组
    NSMutableArray *_CityAry;              //只装城市的数组
    NSMutableArray *_DistrictAry;          //只装区的数组（还有县）
    UIPickerView *_pickerView;        //最主要的选择器
    NSInteger _proIndex;            //用于记录选中哪个省的索引
    NSInteger _cityIndex;           //用于记录选中哪个市的索引
    NSInteger _districtIndex;       //用于记录选中哪个区的索引

}


/**
 *  遮盖按钮
 */
@property (nonatomic, strong) UIButton *coverBtn;
/**
 *  工具条
 */
@property (nonatomic,strong) UIView *keyBoardtTool;

/**
 显示地区
 */
@property (nonatomic, weak) UILabel *areaLabel;

@end

@implementation YzPickerView

-(instancetype)initWithIsCity:(BOOL)iscity{
    if (self = [super initWithFrame:CGRectZero]) {
        self.isCity = iscity;
        [self setup];
    }
    return self;
}

//纯代码创建的子控件会调用这个方法
-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}

//从xib创建的子控件会调用这个方法
-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder]) {
        [self setup];
    }
    return self;
}

#pragma mark - 设置UI

-(void)setup{
    //背景
    self.backgroundColor = [UIColor whiteColor];
    
    _ProvinceAry = [NSMutableArray array];
    _CityAry = [NSMutableArray array];
    _DistrictAry = [NSMutableArray array];
    
    if (self.isCity) {
        _AllARY = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Address" ofType:@"plist"]];
        for (NSDictionary *dci in _AllARY) {
            [_ProvinceAry addObject:[[dci allKeys] firstObject]];
        }
    }else{
        _AllARY = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"pickerDatePlist" ofType:@"plist"]];
        _ProvinceAry = _AllARY[0];
        _CityAry = _AllARY[1];
        _DistrictAry = _AllARY[2];
    }

    
    
    
    //创建 pickerView
    _pickerView = [[UIPickerView alloc] init];
    _pickerView.delegate = self;
    _pickerView.dataSource = self;
    [self addSubview:_pickerView];

    
    [_pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.center);
        make.height.mas_equalTo(216);
        make.bottom.mas_equalTo(self.mas_bottom);
    }];
    
    //创建工具条
    [self addSubview:self.keyBoardtTool];
    
    [self.keyBoardtTool mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self);
        make.height.mas_equalTo(40);
        make.left.mas_equalTo(self);
        make.right.mas_equalTo(self);
    }];
    
    UIButton *confirm = [[UIButton alloc] init];
    [self.keyBoardtTool addSubview:confirm];
    
    [confirm mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.keyBoardtTool).offset(-10);
        make.centerY.mas_equalTo(self.keyBoardtTool.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(50, 30));
    }];
    
    [confirm setTintColor:[UIColor orangeColor]];
    [confirm setTitle:@"确认" forState:UIControlStateNormal];
    [confirm setTitleColor:kColorFromRGB(0x212724) forState:UIControlStateNormal];
    confirm.titleLabel.textAlignment = NSTextAlignmentCenter;
    confirm.titleLabel.font = FONT(20);
    [confirm addTarget:self action:@selector(didClickConfirnButton) forControlEvents:UIControlEventTouchUpInside];
    
    // 显示选择的城市区
    UILabel *areaLabel = [[UILabel alloc] init];
    [self.keyBoardtTool addSubview:areaLabel];
    self.areaLabel = areaLabel;
    areaLabel.font = FONT(15);
    areaLabel.textAlignment = NSTextAlignmentCenter;
    areaLabel.textColor = kColorFromRGB(0x878787);
    
    [areaLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.keyBoardtTool);
        make.right.mas_equalTo(confirm.mas_left).offset(-20);
        make.centerY.mas_equalTo(self.keyBoardtTool.mas_centerY);
    }];
    if (!self.isCity) {
        return;
    }
    for (NSDictionary *dci in _AllARY) {
        
        if ([dci objectForKey:_ProvinceAry[_proIndex]]) {
            _CityAry = [NSMutableArray arrayWithArray:[[dci objectForKey:_ProvinceAry[_proIndex]] allKeys]];
            
            [_pickerView reloadComponent:1];
            [_pickerView selectRow:0 inComponent:1 animated:YES];
            
            NSLog(@"%@",[[dci objectForKey:_ProvinceAry[_proIndex]] objectForKey:_CityAry[0]]);
            
            _DistrictAry = [NSMutableArray arrayWithArray:[[dci objectForKey:_ProvinceAry[_proIndex]] objectForKey:_CityAry[0]]];
            [_pickerView reloadComponent:2];
            [_pickerView selectRow:0 inComponent:2 animated:YES];
            
            
        }
    }
    
}

#pragma mark - 响应事件

/**
 点击了确认
 */
-(void)didClickConfirnButton {
    
    // 如果 label 没值就 return
    if (self.areaLabel.text.length == 0) {
        return;
    }
    
    // 利用 block 传值出去
    if(self.pickerViewValueChangeBlock){
        self.pickerViewValueChangeBlock(self.areaLabel.text);
    }
    [self dismiss];

}

//显示
-(void)show {
    
    //获取window主窗口 直接添加上去,这样做的好去就是不与任何类有关联
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    [window addSubview:self.coverBtn];
    [window addSubview:self];
//    self.backgroundColor = globalColor;
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(window.mas_bottom);
        make.left.mas_equalTo(window);
        make.right.mas_equalTo(window);
        make.height.mas_equalTo(256);
    }];
    
    [self.coverBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(window);
        make.left.mas_equalTo(window);
        make.right.mas_equalTo(window);
        make.height.mas_equalTo(screenH - 256);
    }];
}

//隐藏
-(void)dismiss{
    
    // 以动画形式隐藏日期选择控件
    [UIView animateWithDuration:0.25 animations:^{
        self.frame = CGRectMake(0, screenH , screenW, self.frame.size.height);
    } completion:^(BOOL finished) {
        // 移除控件
        [self.coverBtn removeFromSuperview];
        [self removeFromSuperview];
    }];
}


#pragma mark - 实现 UIPickerView 代理方法
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    if(!self.isCity){
        if (component == 0) {
            _proIndex = row;
            _cityIndex = 0;
            _districtIndex = 0;
            self.areaLabel.text = [NSString stringWithFormat:@"%@%@%@",_ProvinceAry[_proIndex],_CityAry[_cityIndex],_DistrictAry[_districtIndex]];
        }else if(component == 1){
            _cityIndex = row;
            _districtIndex = 0;
            self.areaLabel.text = [NSString stringWithFormat:@"%@%@%@",_ProvinceAry[_proIndex],_CityAry[_cityIndex],_DistrictAry[_districtIndex]];
        }else if(component == 2){
            _districtIndex = row;
            self.areaLabel.text = [NSString stringWithFormat:@"%@%@%@",_ProvinceAry[_proIndex],_CityAry[_cityIndex],_DistrictAry[_districtIndex]];
        }
    }
    
    
    if (component == 0) {
        _proIndex = row;
        _cityIndex = 0;
        _districtIndex = 0;
        
        if (!self.isCity) {
            return;
        }
        
        for (NSDictionary *dci in _AllARY) {
            
            if ([dci objectForKey:_ProvinceAry[_proIndex]]) {
                _CityAry = [NSMutableArray arrayWithArray:[[dci objectForKey:_ProvinceAry[_proIndex]] allKeys]];
                
                [_pickerView reloadComponent:1];
                [_pickerView selectRow:0 inComponent:1 animated:YES];
                
                _DistrictAry = [NSMutableArray arrayWithArray:[[dci objectForKey:_ProvinceAry[_proIndex]] objectForKey:_CityAry[0]]];
                [_pickerView reloadComponent:2];
                [_pickerView selectRow:0 inComponent:2 animated:YES];
                
                
                    self.areaLabel.text = [NSString stringWithFormat:@"%@ - %@ - %@",_ProvinceAry[_proIndex],_CityAry[_cityIndex],_DistrictAry[_districtIndex]];
                }
        }
        
    }
    
    if (component == 1) {
        _cityIndex = row;
        _districtIndex = 0;
        
        if (!self.isCity) {
            return;
        }
        for (NSDictionary *dci in _AllARY) {
            
            if ([dci objectForKey:_ProvinceAry[_proIndex]]) {
                _DistrictAry = [[dci objectForKey:_ProvinceAry[_proIndex]] objectForKey:_CityAry[_cityIndex]];
                [_pickerView reloadComponent:2];
                [_pickerView selectRow:0 inComponent:2 animated:YES];
               
                    self.areaLabel.text = [NSString stringWithFormat:@"%@ - %@ - %@",_ProvinceAry[_proIndex],_CityAry[_cityIndex],_DistrictAry[_districtIndex]];
               

            }
        }
        
    }
    
    if (component == 2) {
        if (!self.isCity) {
            return;
        }
        _districtIndex = row;
        
        self.areaLabel.text = [NSString stringWithFormat:@"%@ - %@ - %@",_ProvinceAry[_proIndex],_CityAry[_cityIndex],_DistrictAry[_districtIndex]];
        
    }
    
    
}

// 告诉pickerView每一行要显示什么内容
- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (component == 0) {
        return [_ProvinceAry objectAtIndex:row];
    }else if (component == 1){
        return [_CityAry objectAtIndex:row];
    }else if (component == 2){
        return [_DistrictAry objectAtIndex:row];
    }
    
    return nil;
}
//自定义每个pickview的label
-(UIView*)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
//    UILabel* pickerLabel = [UILabel new];
    UILabel *pickerLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, [pickerView rowSizeForComponent:component].width - 12, [pickerView rowSizeForComponent:component].height)];
    pickerLabel.numberOfLines = 0;
    pickerLabel.textAlignment = NSTextAlignmentCenter;
    [pickerLabel setFont:[UIFont boldSystemFontOfSize:15]];
//    pickerLabel.backgroundColor = [UIColor redColor];
    pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

#pragma mark - 实现 UIPickerView 数据源方法
// 告诉pickerView每列有多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component==0) {
        return _ProvinceAry.count;
    }else if (component == 1){
        return _CityAry.count;
    }else if (component == 2){
        return _DistrictAry.count;
    }
    
    return 0;
}
// 告诉pickerView要显示多少列数据
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}


#pragma mark - 懒加载

/**
 *  遮罩
 */
- (UIButton *)coverBtn {
    if (_coverBtn == nil) {
        _coverBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_coverBtn addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
//        _coverBtn.backgroundColor = globalColor;
//        _coverBtn.alpha = 0.1;
    }
    return _coverBtn;
}

/**
 *  工具条
 */
-(UIView *)keyBoardtTool {
    if (_keyBoardtTool == nil) {
        _keyBoardtTool = [[UIView alloc] init];
        _keyBoardtTool.backgroundColor = kColorFromRGB(0xececec);
    }
    return _keyBoardtTool;
}

#pragma mark - dealloc
-(void)dealloc
{
    NSLog(@"%s",__func__);
}


@end
